const config = require('./config')
let times = 0, timeoutId = null, loadingShowed = false

/**
 * 网络请求封装
 * @param url {string} 请求接口地址
 * @param method {'GET'|'POST'} 请求方法
 * @param [data] {IAnyObject} 请求数据
 * @param [setting] {XCIRequestOption} 请求设置
 * @return {Promise<Object>}
 */
function request(url, method, data, setting) {
  if (!setting) setting = {}
  if (setting.loading === null || setting.loading === undefined) setting.loading = config.requestDefaultLoading
  if (setting.pageSize === null || setting.pageSize === undefined) setting.pageSize = false

  //region 请求加载提示
  if (setting.loading && times === 0 && timeoutId === null) {
    timeoutId = setTimeout(function () {
      wx.showLoading({
        title: setting.loading,
        mask: true
      })
      loadingShowed = true
    }, config.requestLoadingDelay || 500)
  }
  //endregion

  //region 初始化 Data
  if (!data) data = {}
  if (setting.pageSize === true) {
    data = {...setting.data, ...data, pageSize: config.pageSize}
  }
  //endregion

  //region 初始化 Header
  const header = {
    ...config.getDefaultHeader(),
    ...setting.header
  }
  //endregion

  times++
  return new Promise((resolve, reject) => {
    wx.request({
      ...setting,
      url: config.getApiUrl(url),
      data,
      method,
      header,
      success: (res) => {
        if (setting.responseType === 'arraybuffer') {
          resolve(res.data)
        } else {
          if (res.data['success'] === true) {
            resolve(res.data)
          } else if (config.handleError(res.data) !== true) {
            reject(res.data)
          }
        }
      },
      fail: (err) => {
        console.error('request fail', err)
      },
      complete: () => {
        times--
        if (setting.loading && times === 0) {
          if (timeoutId) clearTimeout(timeoutId)
          if (loadingShowed === true) wx.hideLoading()

          timeoutId = null
          loadingShowed = false
        }
      }
    })
  })
}

/**
 * GET网络请求
 * @param url {string} 请求接口地址
 * @param [data] {IAnyObject} 请求数据
 * @param [setting] {XCIRequestOption} 请求设置
 * @return {Promise<Object>}
 */
function get(url, data, setting) {
  return request(url, 'GET', data, setting)
}

/**
 * POST网络请求
 * @param url {string} 请求接口地址
 * @param [data] {IAnyObject} 请求数据
 * @param [setting] {XCIRequestOption} 请求设置
 * @return {Promise<Object>}
 */
function post(url, data, setting) {
  return request(url, 'POST', data, setting)
}

module.exports = {
  get,
  post
}